<template>
	<view>
		<view class="tabBox">
			<scroll-view scroll-x="true" :scroll-left="scrollLeft" :scroll-with-animation="true">
				<view class="box">
					<view class="tabItem" v-for="(item,index) in typeList" :key="index"
						:class="{'ac':tabCurrent == index}" @click="tabChange(index,item.title)">
						{{item.title}}
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			typeList: [String, Array],
			moType: [String, Array, Number],
		},
		data() {
			return {
				itemWidth: 0, //每个item的宽度
				scrollLeft: 0, //滑动距离
				tabCurrent: 0, //默认当前月份
				sendMonth: '',

			}
		},
		watch: {
			moType(newVal, oldVal) {
				this.tabCurrent = newVal
				this.scrollLeftEvent()
			},
		},
		mounted() {
			// 先获取当前时间的月份
			let date = new Date();
			this.tabCurrent = this.moType || 0 // getMonth()返回的月份从0开始  正好符合tabCurrent  不用再加1了
			this.sendMonth = date.getMonth() + 1; // 初次加载，传当前月份

			this.scrollLeftEvent()
		},
	
		methods: {
			scrollLeftEvent(){
				setTimeout(() => {
					this.$nextTick(() => {
						const query = uni.createSelectorQuery().in(this);
						query.select('.tabItem').boundingClientRect(data => {
							// item宽度 = 自身宽度 + 8px右边距
							this.itemWidth = data.width;
							this.scrollLeft = this.itemWidth * (this.tabCurrent - 1);
						}).exec();
					})
				}, 1000)
			},
			// 点击tab切换高亮，并进行滑动，（index-1）是为了点击项显示在第二栏的位置
			tabChange(index, type) {
				this.tabCurrent = index;
				// 传参的月份
				// this.sendMonth = this.typeList[index].id
				this.scrollLeft = this.itemWidth * (index - 1);
				console.log(this.scrollLeft);
				this.$emit('tabChangeType', type)
			},
		}
	}
</script>
<style lang="scss">
	.tabBox {
		background: #ffffff;

		/* 隐藏滚动条样式 */
		::-webkit-scrollbar {
			width: 0;
			height: 0;
		}

		.box {
			// width: 1400rpx;
			min-width: 100rpx;
			margin: 0 5rpx;
			display: flex;
			align-items: center;
			height: 90rpx;

			.tabItem {
				flex-shrink: 0;
				text-align: center;
				width: auto;
				min-width: 100rpx;



				// display: inline-block;
				width: auto;
				text-align: center;
				padding: 16rpx 44rpx;
				/* border: 1px solid #ccc; */
				margin-left: 26rpx;
				box-sizing: border-box;
				border-radius: 36rpx;
				background: #E4E4E4;
				font-size: 32rpx;
				color: #666;
			}

			.ac {
				background: #9013FE;
				font-size: 28rpx;
				color: #FFFFFF;
			}
		}
	}
</style>